package cn.easyplatform.studio.web.servlet;

import cn.easyplatform.lang.Streams;
import cn.easyplatform.lang.Strings;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.web.servlet.http.Https;
import org.zkoss.zk.ui.*;
import org.zkoss.zk.ui.http.ExecutionImpl;
import org.zkoss.zk.ui.http.I18Ns;
import org.zkoss.zk.ui.http.WebManager;
import org.zkoss.zk.ui.impl.RequestInfoImpl;
import org.zkoss.zk.ui.metainfo.PageDefinition;
import org.zkoss.zk.ui.sys.RequestInfo;
import org.zkoss.zk.ui.sys.SessionCtrl;
import org.zkoss.zk.ui.sys.UiFactory;
import org.zkoss.zk.ui.sys.WebAppCtrl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;

@WebServlet(name = "richletServlet",urlPatterns = "/richlet/dyamic")
public class StudioServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String compose=request.getParameter("compose");
        String xul = (String) request.getSession().getAttribute(compose);
        response.setHeader( "Pragma", "no-cache" );
        response.setDateHeader("Expires", 0);
        response.addHeader( "Cache-Control", "no-cache" );//浏览器和缓存服务器都不应该缓存页面信息
        response.addHeader( "Cache-Control", "no-store" );//请求和响应的信息都不应该被存储在对方的磁盘系统中；
        response.addHeader( "Cache-Control", "must-revalidate" );
        if(Strings.isBlank(xul))
            return;
        final WebManager webman = WebManager.getWebManager(this.getServletContext());
        final WebApp wapp = webman.getWebApp();
        final WebAppCtrl wappc = (WebAppCtrl) wapp;
        final Session sess = WebManager.getSession(this.getServletContext(), request);
        final Object old = I18Ns.setup(sess, request, response, "utf-8");
        StringWriter out = null;
        OutputStream os = null;
        String result = null;
        try {
            final String path = Https.getThisServletPath(request);
            final Desktop desktop = webman.getDesktop(sess, request, response,
                    path, true);
            if (desktop == null)
                return;

            final RequestInfo ri = new RequestInfoImpl(wapp, sess, desktop,
                    request, null);
            ((SessionCtrl) sess).notifyClientRequest(true);
            final UiFactory uf = wappc.getUiFactory();
            PageDefinition pagedef = uf.getPageDefinitionDirectly(ri, xul,
                    "zul");
            final Page page = WebManager.newPage(uf, ri, pagedef, response,
                    path);
            final Execution exec = new ExecutionImpl(this.getServletContext(), request, response,
                    desktop, page);
            out = new StringWriter(4096 * 2);
            wappc.getUiEngine().execNewPage(exec, pagedef, page, out);
            String cs = response.getCharacterEncoding();
            if (cs == null || cs.length() == 0)
                cs = "UTF-8";
            result = out.toString();
            os = response.getOutputStream();
            byte[] data = result.getBytes(cs);
            if (!Servlets.isIncluded(request) && data.length > 200) {
                byte[] bs = Https.gzip(request, response, null, data);
                if (bs != null)
                    data = bs;
            }
            response.setContentLength(data.length);
            os.write(data);
            os.flush();
        } catch (IllegalStateException ex) {
            if (result != null)
                response.getWriter().write(result);
            else
                throw ex;
        } catch (UiException ex) {
            throw ex;
        } finally {
            Streams.safeClose(out);
            Streams.safeClose(os);
            I18Ns.cleanup(request, old);
        }
    }
}
